class: directive

Posted on 2023-02-04 by

henrikvilhelmberglund

We know how to set a class using the class attribute :

0

App.svelte

<script>
	let profit = 0;
</script>

<div class="{profit < 0 ? 'negative' : ''} {profit > 0 ? 'positive' : ''}">
	<span class="p-4 font-serif text-2xl">{profit}</span>
	<button class="p-4" on:click={() => profit++}>++</button>
	<button class="p-4" on:click={() => profit--}>--</button>
</div>

<style>
	.negative {
		color: red;
		font-weight: bold;
	}
	.positive {
		color: limegreen;
		font-weight: bold;
	}
</style>

        

But in Svelte there's another way to set classes using something called a class directive .

A directive in Svelte is anything with a colon .

To write a class directive we write class: followed by the class name , followed by an equals sign and the condition for the class to apply .

0

ClassDirective.svelte

<script>
	let profit = 0;
</script>

<div class:negative={profit < 0} class:positive={profit > 0}>
	<span class="p-4 font-serif text-2xl">{profit}</span>
	<button class="p-4" on:click={() => profit++}>++</button>
	<button class="p-4" on:click={() => profit--}>--</button>
</div>

<style>
	.negative {
		color: red;
		font-weight: bold;
	}
	.positive {
		color: limegreen;
		font-weight: bold;
	}
</style>

        

We can use a shorthand by setting the expression to a reactive variable .

0

ClassDirective2.svelte

<script>
	let profit = 0;
	$: negative = profit < 0;
	$: positive = profit > 0;
</script>

<!-- same thing as 
<div class:negative={negative} class:positive={positive}> -->
<div class:negative class:positive>
	<span class="p-4 font-serif text-2xl">{profit}</span>
	<button class="p-4" on:click={() => profit++}>++</button>
	<button class="p-4" on:click={() => profit--}>--</button>
</div>

<style>
	.negative {
		color: red;
		font-weight: bold;
	}
	.positive {
		color: limegreen;
		font-weight: bold;
	}
</style>